import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:travel/model/review.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class VisitorReviewPageState extends StatefulWidget {
  const VisitorReviewPageState({super.key});

  @override
  State<VisitorReviewPageState> createState() => _VisitorReviewPageStateState();
}

class _VisitorReviewPageStateState extends State<VisitorReviewPageState> {
  List<String> tags = ['全部 5787', '视频图片 23/47', '好评 4670', '最新'];

  int tagIndex = 0;

  List<VisitorReviewModel> pageList = [];

  bool isLoading = false;

  bool hasNext = true;

  int total = 20;

  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    initData();
    scrollController.addListener(() {
      if (!isLoading &&
          hasNext &&
          scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
        setState(() {
          isLoading = true;
        });
        loadMoreData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          height: 50.h,
          padding: EdgeInsets.symmetric(horizontal: 15.w),
          alignment: Alignment.centerLeft,
          child: Wrap(
            spacing: 5.w,
            children: tags
                .asMap()
                .map((index, tag) {
                  double w = ToolsUtils.calculateTextHeight(
                      context, tag, FontWeight.normal, 12.sp, 100.w, 1);
                  return MapEntry(
                      index,
                      InkWell(
                          onTap: () {
                            setState(() {
                              tagIndex = index;
                            });
                          },
                          child: Container(
                            height: 30.h,
                            width: w + 20.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: getBackgroundColor(index),
                                borderRadius: BorderRadius.circular(15.h)),
                            child: Text(tag, style: getLabelStyle(index)),
                          )));
                })
                .values
                .toList(),
          ),
        ),
        Expanded(
            child: ListView.builder(
          controller: scrollController,
          padding: EdgeInsets.symmetric(horizontal: 10.w),
          itemBuilder: (BuildContext context, int index) {
            if (index < pageList.length) {
              var row = pageList[index];
              return Container(
                margin: EdgeInsets.only(bottom: 15.h),
                child: Column(
                  children: [
                    SizedBox(
                      height: 40.h,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CircleAvatar(
                            radius: 20.w,
                            backgroundColor: Colors.transparent,
                            backgroundImage: NetworkImage(
                              row.avatar,
                            ),
                          ),
                          Expanded(
                              child: Column(
                            children: [
                              Container(
                                height: 20.h,
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  row.nickname,
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color3333, fontSize: 15.sp),
                                ),
                              ),
                              Container(
                                alignment: Alignment.centerLeft,
                                margin: EdgeInsets.only(top: 5.h),
                                child: Text(
                                  '${row.date}  ${row.from}',
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color9999, fontSize: 12.sp),
                                ),
                              )
                            ],
                          )),
                          Align(
                              alignment: Alignment.topRight,
                              child: Text.rich(TextSpan(children: [
                                WidgetSpan(
                                    child: ToolsUtils.assetImageSvg('u791.svg',
                                        width: 16.sp, height: 16.sp),
                                    alignment: PlaceholderAlignment.middle),
                                TextSpan(
                                    text: '${row.like > 0 ? row.like : ''}',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color6666, fontSize: 12.sp))
                              ])))
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(vertical: 10.h),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        row.introduce,
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                        style: StylesUtils.customTextStyle(
                            fontSize: 15.sp, color: ColorsUtils.color3333, lineHeight: 1.5.h),
                      ),
                    ),
                    StaggeredGrid.count(
                      crossAxisCount: 3,
                      crossAxisSpacing: 8.w,
                      mainAxisSpacing: 8.w,
                      children: row.photos
                          .map((e) => ClipRRect(
                                borderRadius: BorderRadius.circular(8.w),
                                child: CachedNetworkImage(
                                  imageUrl: e,
                                  alignment: Alignment.topLeft,
                                  fit: BoxFit.cover,
                                  height: 110.h,
                                  placeholder: (context, url) => const CircularProgressIndicator(),
                                ),
                              ))
                          .toList(),
                    )
                  ],
                ),
              );
            }
            if (!hasNext) {
              return notDataBottom();
            }
            return renderBottom();
          },
          itemCount: pageList.length + 1,
        )),
        Container(
          height: 70.h,
          padding: EdgeInsets.only(left: 15.w, right: 15, top: 10.h),
          alignment: Alignment.centerLeft,
          color: Colors.white,
          child: Container(
            height: 40.h,
            decoration: BoxDecoration(
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF5f5),
                borderRadius: BorderRadius.circular(20.w)),
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            alignment: Alignment.centerLeft,
            child: TextButton(
              onPressed: () {
                Get.toNamed(RoutePath.comment);
              },
              child: Text.rich(TextSpan(children: [
                WidgetSpan(
                    child: ToolsUtils.assetImageSvg('u775.svg', width: 15, height: 15.h),
                    alignment: PlaceholderAlignment.middle),
                TextSpan(
                    text: '写评论…',
                    style:
                        StylesUtils.customTextStyle(color: ColorsUtils.color9999, fontSize: 13.sp))
              ])),
            ),
          ),
        )
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  void initData() {
    pageList.add(VisitorReviewModel(
        avatar:
            'https://img2.baidu.com/it/u=359052501,4040079240&fm=253&app=53&size=f60,60&n=0&g=0n&f=jpeg&fmt=auto?sec=1707034614&t=975d5a6b28b4bca430453f56adb4e856',
        date: '2023-10-11',
        nickname: '横****笑',
        from: '来自辽宁',
        introduce: '故宫是一个5A级景区，其实这里是中国封建王朝的首都皇帝的居住地，面积非常大，游览下来需要一天整时间，故宫前前后后见了糟了几百年，也有几十',
        photos: [
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        ]));
    pageList.add(VisitorReviewModel(
        avatar:
            'https://img2.baidu.com/it/u=359052501,4040079240&fm=253&app=53&size=f60,60&n=0&g=0n&f=jpeg&fmt=auto?sec=1707034614&t=975d5a6b28b4bca430453f56adb4e856',
        date: '2023-10-11',
        nickname: 'M****0',
        from: '来自辽宁',
        introduce: '当然值得去，文化遗产，第一批全国重点文物保护单位，可看的太多了。有时一天只转一两个殿，里面的展览精彩啊。比如武英殿，陶瓷馆的展览仔细看的…',
        like: 14,
        photos: [
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        ]));
    pageList.add(VisitorReviewModel(
        avatar:
            'https://img2.baidu.com/it/u=359052501,4040079240&fm=253&app=53&size=f60,60&n=0&g=0n&f=jpeg&fmt=auto?sec=1707034614&t=975d5a6b28b4bca430453f56adb4e856',
        date: '2023-10-11',
        nickname: '爱旅游的小A',
        from: '来自吉林',
        introduce: '故宫规模之大，建筑之多，一排排红一墙金顶的建筑整齐排列，倘若登在高处由南向北远眺俯视，更能让人感觉到它的气势宏伟。在中国乃至世界，规模如',
        like: 32,
        photos: [
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
          'https://img1.baidu.com/it/u=3289240402,3021202551&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        ]));
  }

  Future<void> loadMoreData() async {
    return Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        if (total > pageList.length) {
          hasNext = true;
          isLoading = false;
          initData();
        } else {
          hasNext = false;
          isLoading = false;
        }
      });
    });
  }

  TextStyle getLabelStyle(int index) {
    if (index == tagIndex) {
      return StylesUtils.customTextStyle(fontSize: 12.sp, color: ColorsUtils.color3478);
    }
    return StylesUtils.customTextStyle(fontSize: 12.sp, color: ColorsUtils.color3333);
  }

  Color getBackgroundColor(int index) {
    if (index == tagIndex) {
      return ColorsUtils.parseColorFromHexString('#ebf6ff');
    }
    return ColorsUtils.parseColorFromHexString('#eaf0f6');
  }

  Widget notDataBottom() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '已经到底',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    );
  }

  Widget renderBottom() {
    if (isLoading) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      );
    }
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    );
  }
}
